#include "spi.h"
#include <targets/lpc21xx.h>

/******************************************************************************/
/** \file spi.c
 *  \brief Driver code lpc2106 SPI peripheral.
 *  \author Iain Derrington (www.kandi-electronics.com)
 *  \date 0.1 20/06/07 First draft
 */
/*******************************************************************************/


/***********************************************************************/
/** \brief Initilialise the SPI peripheral
 *
 * Description: init the LPC2106 SPI peripheral. Simple non flexible version
 *              
 *              
 * \author Iain Derrington

 */
/**********************************************************************/
void initSPI(void)
{
    u16_t i;

    // configure LPC2106
    PINSEL0 = 0x5500;              // read current contents of PINSEL0
    

    // configure LPC2106 spi registers
    S0SPCCR = 9;               
    S0SPCR  = S0SPCR_MSTR;      // spi module in master mode, CPOL = 0, CCPHA = 0. MSB first
    
    i = S0SPSR;                // read SPI status reg to clear the flags.
}

/***********************************************************************/
/** \brief SPiWrite 
 *
 * Description: Writes bytes from buffer to SPI tx reg

 * \author Iain Derrington
 * \param ptrBuffer Pointer to buffer containing data.
 * \param ui_Len number of bytes to transmit.
 * \return uint Number of bytes transmitted.
 */
/**********************************************************************/
u16_t SPIWrite(u8_t * ptrBuffer, u16_t ui_Len)
{
  u16_t i,stat;
  
  stat= S0SPSR;
  
  if (ui_Len == 0)           // no data no send
    return 0;

    for (i=0;i<ui_Len;i++)
    {
      S0SPDR= *ptrBuffer++;     // load spi tx reg
      while(!(S0SPSR)){}   // wait for transmission to complete
    }

    return i;
}

/***********************************************************************/
/** \brief SPIRead
 *
 * Description: Will read ui_Length bytes from SPI. Bytes placed into ptrbuffer

 * \author Iain Derrington
 * \param ptrBuffer Buffer containing data.
 * \param ui_Len Number of bytes to read.
 * \return uint Number of bytes read.
 */
/**********************************************************************/
u16_t SPIRead(u8_t * ptrBuffer, u16_t ui_Len)
{
u16_t i,stat;

  stat= S0SPSR;

  for (i=0;i<ui_Len;i++)
  {
    S0SPDR= 0xff;                  // dummy transmit byte
    
    while(!(S0SPSR))                // wait for transmission to complete
    {
    }   
                         
    *ptrBuffer++ = S0SPDR;              // read data from SPI data reg, place into buffer
  }
  return i;
}
